package com.yaozheng.vocationaltraining.fragment;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.PKCategoryAdapter;
import com.yaozheng.vocationaltraining.adapter.PKGameCategoryAdapter;
import com.yaozheng.vocationaltraining.bean.PKCategoryBean;
import com.yaozheng.vocationaltraining.bean.PKGameCategoryBean;
import com.yaozheng.vocationaltraining.bean.PKRankBean;
import com.yaozheng.vocationaltraining.iview.IPKGameCategoryView;
import com.yaozheng.vocationaltraining.service.exam.PKGameCategoryService;
import com.yaozheng.vocationaltraining.service.exam.PKService;
import com.yaozheng.vocationaltraining.service.impl.exam.PKGameCategoryServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.exam.PKServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.widget.CircleImageView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * Created by moon on 2017/11/14.
 */

@EFragment(R.layout.activity_pk_game_category)
public class PKGameCategoryFragment extends BaseFragment
        implements IPKGameCategoryView {

    @ViewById
    GridView gridview;

    PKGameCategoryAdapter pkGameCategoryAdapter;
    ArrayList<PKGameCategoryBean> pkGameCategoryData = new ArrayList<>();

    @ViewById
    TextView headTitleText;
    @ViewById
    TextView headRightText;

    @ViewById
    TextView jifeng_number_textview;
    @ViewById
    CircleImageView userAvatarImage;
    @ViewById
    TextView username_textview;
    @ViewById
    TextView winning_textview;

    @Bean(PKGameCategoryServiceImpl.class)
    PKGameCategoryService pkGameCategoryService;

    private BitmapLoader userBitmapLoader;

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    @AfterViews
    public void initView() {
        headTitleText.setText("PK赛");
        pkGameCategoryService.init(this);
        userBitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);

        headRightText.setText("排行榜");
        headRightText.setVisibility(View.VISIBLE);
        headRightText.setTextColor(this.getActivity().
                getResources().getColor(R.color.black));

        pkGameCategoryAdapter = new PKGameCategoryAdapter(this.getActivity(),
                pkGameCategoryData);
        gridview.setAdapter(pkGameCategoryAdapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (pkGameCategoryData.get(i).getPlayerLimit() == 1){ // 与系统PK ，TODO TEST MOON
                    showOperatingProgressDialog("获取试卷中...");
                    pkGameCategoryService.loadQuestionList(
                            pkGameCategoryData.get(i).getId(),
                            pkGameCategoryData.get(i).getName());
                }else if (pkGameCategoryData.get(i).getPlayerLimit() == 2 ||
                        pkGameCategoryData.get(i).getPlayerLimit() == 3){
                    getHomeActivity().openPKHallFragment(
                            pkGameCategoryData.get(i).getId(),
                            pkGameCategoryData.get(i).getPlayerLimit());
                }else {//进入多人PK赛列表
                    getHomeActivity().openPKMorePersonHallFragment(
                            pkGameCategoryData.get(i).getId());
                }

            }
        });

        username_textview.setText(name);
        jifeng_number_textview.setText(jifengNumber+"");
        //加载图片
        userBitmapLoader.displayImage(avatarUrl, userAvatarImage);
        if (winRate != 0){
            winning_textview.setText(winRate/ 100.0+"");
        }else {
            winning_textview.setText("--");
        }

        onRefresh();

    }

    private void onRefresh() {
        pkGameCategoryService.list(paperCateId);
    }

    @Click(R.id.headRightText)
    public void headRightTextClick() {//打开排行榜界面
        getHomeActivity().openPKRankFragment(name,
                avatarUrl,
                jifengNumber,
                winRate);
    }



    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","game-cates");
            if (dataList != null) {
                pkGameCategoryData.clear();

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    PKGameCategoryBean bean = new PKGameCategoryBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setName(jsonObject2.getString("name"));
                    bean.setIcon(jsonObject2.getString("icon"));
                    bean.setPlayerLimit(jsonObject2.getInt("playerLimit"));

                    pkGameCategoryData.add(bean);
                }

                pkGameCategoryAdapter.setData(pkGameCategoryData);
                pkGameCategoryAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @Override
    public void responseError(String error) {

    }









    int jifengNumber;
    String name;
    String avatarUrl;
    int winRate;

    public int getPaperCateId() {
        return paperCateId;
    }

    public void setPaperCateId(int paperCateId) {
        this.paperCateId = paperCateId;
    }

    int paperCateId;

    public int getJifengNumber() {
        return jifengNumber;
    }

    public void setJifengNumber(int jifengNumber) {
        this.jifengNumber = jifengNumber;

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;

    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;

    }

    public int getWinRate() {
        return winRate;
    }

    public void setWinRate(int winRate) {
        this.winRate = winRate;

    }


    @UiThread
    @Override
    public void getQuestionListSuccess(JSONObject jsonObject,String name) {
        cancelOperatingProgressDialog();
        JSONObject paperJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "game","paper");
        if(!paperJsonObject.containsKey("duration")){
            paperJsonObject.put("duration",TypeUtils.getJsonObject(jsonObject,
                    "data", "game").getInt("duration"));
        }
        // 进入考试
        Intent intent = getBaseActivity().getIntent();
        intent.putExtra("examType", "8");//8表示PK赛
        intent.putExtra("isSystemPK", true);//表示与系统 PK
        intent.putExtra("paperId",
                TypeUtils.getJsonInteger(paperJsonObject, "id"));
        intent.putExtra("startTimeLong", System.currentTimeMillis());
        intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
        intent.putExtra("examTitle", name);
        getHomeActivity().openOnlineExamFragment();
    }

    @UiThread
    @Override
    public void getQuestionListError(String error) {
        Toast.makeText(this.getHomeActivity(),error,Toast.LENGTH_SHORT).show();
    }
}
